<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select v-model="formData.planId" placeholder="请选择评价计划" style="width: 100%">
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input v-model="formData.name" placeholder="请输入姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="身份证号" prop="idNumber">
            <el-input v-model="formData.idNumber" placeholder="请输入身份证号" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="formData.gender">
              <el-radio :value="1">男</el-radio>
              <el-radio :value="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="formData.birthDate"
              type="date"
              placeholder="选择出生日期"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="联系电话" prop="mobile">
            <el-input v-model="formData.mobile" placeholder="请输入联系电话" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入电子邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="工作单位" prop="workUnit">
            <el-input v-model="formData.workUnit" placeholder="请输入工作单位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="部门" prop="department">
            <el-input v-model="formData.department" placeholder="请输入部门" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="职位" prop="position">
            <el-input v-model="formData.position" placeholder="请输入职位" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工作年限" prop="workYears">
            <el-input-number v-model="formData.workYears" :min="0" placeholder="工作年限" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="申报职业" prop="appliedProfession">
            <el-input v-model="formData.appliedProfession" placeholder="请输入申报职业" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="申报等级" prop="appliedLevel">
            <el-input v-model="formData.appliedLevel" placeholder="请输入申报等级" />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="数据来源" prop="dataSource">
            <el-select v-model="formData.dataSource" placeholder="请选择数据来源">
              <el-option label="手动录入" :value="1" />
              <el-option label="批量导入" :value="2" />
              <el-option label="系统同步" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报名状态" prop="registrationStatus">
            <el-select v-model="formData.registrationStatus" placeholder="请选择报名状态">
              <el-option label="已报名" :value="1" />
              <el-option label="已确认" :value="2" />
              <el-option label="已取消" :value="3" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注信息" prop="remarks">
        <el-input
          v-model="formData.remarks"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="submitForm" type="primary" :loading="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import * as EvalCandidateApi from '@/api/eval/candidate/index'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['success'])
const dialogVisible = ref(false)
const dialogTitle = computed(() => (formData.value.id ? '修改参评人员' : '添加参评人员'))
const formLoading = ref(false)
const formRef = ref()
const planList = ref([])
const formData = ref({
  id: undefined,
  planId: undefined,
  candidateId: undefined,
  name: '',
  idNumber: '',
  mobile: '',
  email: '',
  gender: 1,
  birthDate: '',
  workUnit: '',
  department: '',
  position: '',
  workYears: 0,
  appliedLevel: '',
  appliedProfession: '',
  dataSource: 1,
  importBatchId: '',
  registrationStatus: 1,
  registrationTime: undefined,
  confirmationTime: undefined,
  remarks: ''
})
const formRules = ref({
  planId: [{ required: true, message: '评价计划不能为空', trigger: 'change' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  idNumber: [
    { required: true, message: '身份证号不能为空', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  mobile: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  appliedLevel: [{ required: true, message: '申报等级不能为空', trigger: 'blur' }]
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  resetForm()
  if (id) {
    formLoading.value = true
    try {
      const data = await EvalCandidateApi.getCandidateInfo(id)

      // 处理出生日期格式转换
      if (data.birthDate) {
        if (Array.isArray(data.birthDate) && data.birthDate.length >= 3) {
          // 如果是数组格式 [year, month, day]，转换为 YYYY-MM-DD 格式
          const [year, month, day] = data.birthDate
          data.birthDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
        }
      }

      Object.assign(formData.value, data)
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const submitForm = async () => {
  const elForm = formRef.value
  if (!elForm) return
  const valid = await elForm.validate()
  if (!valid) return
  formLoading.value = true
  try {
    const data = formData.value
    if (data.id) {
      await EvalCandidateApi.updateCandidateInfo(data)
      ElMessage.success('修改成功')
    } else {
      await EvalCandidateApi.createCandidateInfo(data)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    planId: undefined,
    candidateId: undefined,
    name: '',
    idNumber: '',
    mobile: '',
    email: '',
    gender: 1,
    birthDate: '',
    workUnit: '',
    department: '',
    position: '',
    workYears: 0,
    appliedLevel: '',
    appliedProfession: '',
    dataSource: 1,
    importBatchId: '',
    registrationStatus: 1,
    registrationTime: undefined,
    confirmationTime: undefined,
    workExperience: 0,
    remarks: ''
  }
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

/** 获取评价计划列表 */
const getPlanList = async () => {
  try {
    // TODO: 调用评价计划API获取列表
    // const data = await EvalPlanApi.getEvalPlanList()
    // planList.value = data

    // 临时模拟数据
    planList.value = [
      { id: 1, planName: '2024年技能评价计划' },
      { id: 2, planName: '2024年专业技术评价计划' }
    ]
  } catch (error) {
    console.error('获取评价计划列表失败:', error)
  }
}

// 组件挂载时获取评价计划列表
onMounted(() => {
  getPlanList()
})

defineExpose({ open })
</script> 